<?php 
class Channel {
	
	public static function get($id=null){
		static $datas;
		if (!$datas) {
			if (!$datas = \mylib\Cache::get('channels')) {
				$db = new \Medoo\Medoo(\mylib\Config::get('database'));
				$tmp = $db -> select('channel', '*', ['status'=>1]);
				$datas = [];
				foreach ($tmp as $key => $value) {
					$datas[$value['id']] = $value;
				}
				\mylib\Cache::set('channels', $datas, 3600);
			}
		}
		if (is_null($id)) {
			return $datas;
		}elseif ($id) {
			return isset($datas[$id])?$datas[$id]:null;
		}else{
			return null;
		}
	}

	public static function top($id){
		if ($data = self::get($id)) {
			if (!$data['pid']) {
				return $data;
			}
			return self::top($data['pid']);
		}
		return null;
	}

	public static function parents($id, &$res){
		if ($data = self::get($id)) {
			$res[] = $data;
			if ($data['pid']) {
				self::parents($data['pid'], $res);
			}
		}
	}
}